import Vue from 'vue'
import Router from 'vue-router'
import { setTransitionName, setPageTitle, cancelRequest } from 'thinkive-hvue'

//可以根据菜单栏目 把页面路由分组到各栏目模块中，再引入来扩展
import TouGu from './tougu'
import Viewpoint from './viewpoint'
Vue.use(Router)
import Index from '@/views/index.vue'
/*
  路由懒加载采用官方推荐的ES6 import()语法，
  webpackChunkName相同会打包成一个模块，不同则为不同模块
*/
console.log(process.env.BASE_URL)
const router = new Router({
  //路由模式：history, hash. 默认设置为 history
  mode: 'hash',
  //采用history模式时，要设置base路径; hash模式不用设置(注释掉)
  //环境变量BASE_URL同步publicPath设置
  // base: process.env.BASE_URL,
  scrollBehavior(to, from, savedPosition) {
    // 页面滚动行为, 保持缓存页面的滚动位置, 否则返回页面顶部
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
  routes: [
    {
      path: '/index',
      name: 'index',
      component: Index,
      meta: {
        title: '首页',
      },
    },
    {
      path: '/',
      redirect: 'index',
    },
    {
      path: '/twopage',
      name: 'twopage',
      component: () => import(/* webpackChunkName: "page" */ '@/views/twopage.vue'),
      meta: {
        title: 'twopage',
      },
      children: [
        {
          path: 'subpage',
          name: 'subpage',
          component: () => import(/* webpackChunkName: "page" */ '@/views/subpage.vue'),
          meta: {
            title: 'subpage',
          },
        },
      ],
    },
    ...TouGu,
    ...Viewpoint,
  ],
})

router.beforeEach((to, from, next) => {
  //页面切换动画
  setTransitionName()
  cancelRequest()
  next()
})

router.afterEach(route => {
  //页面切换更改title
  //这里可以根据业务需求调整取title的顺序
  //默认先取业务跳转参数query中title，再取路由元信息中title
  if (route.query.title) {
    setPageTitle(route.query.title)
  } else if (route.meta.title) {
    setPageTitle(route.meta.title)
  }
})

export default router
